package sh.grapendaal.tsuushin.module.uno.engine.event.dispatcher;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sh.grapendaal.tsuushin.module.uno.engine.event.Event;
import sh.grapendaal.tsuushin.module.uno.engine.event.listener.EventListener;

public abstract class EventDispatcher<T extends Event> {
	private static final Logger LOGGER = LoggerFactory.getLogger(EventDispatcher.class);
	
	private List<EventListener<T>> listeners = new ArrayList<EventListener<T>>();
	
	public void addListener(EventListener<T> listener) {
		this.listeners.add(listener);
	}
	
	public void removeListener(EventListener<T> listener) {
		this.listeners.remove(listener);
	}
	
	protected Iterator<EventListener<T>> getListeners() {
		return this.listeners.iterator();
	}
	
	protected void dispatchEvent(EventRunnable<T> runnable) {
		Iterator<EventListener<T>> iterator = getListeners();
		while (iterator.hasNext()) {
			EventListener<T> listener = iterator.next();
			try {
				runnable.run(listener);
			} catch (RuntimeException e) {
				LOGGER.error("RuntimeException while executing event listener", e);
			}
		}
	}
}
